<template>
	<view class="select_date_wrap">
		<view class="select_date_header">
			<p></p>
			<span>选择就餐时间</span>
			<p @click="selectDateConfirm">确定</p>
		</view>
		
		<scroll-view scroll-y="true" style="height: calc(70vh - 100rpx);">
			<section style="border-bottom: 1px solid #f4f4f4;">
				<view class="form_item"
					v-for="i in 2" 
					:key="i">
					{{i ? '结束' : '开始'}}时间: 
					<view class="date_block" @click="selectPicker(i)">
						<van-icon name="notes-o" size="32rpx" />
						<p>{{dining_date_[i] || '请选择时间'}}</p>
					</view>
				</view>
			</section>
			
			<view class="appointment_date_wrap">
				<view class="subTitle">
					已被预约时间 
					<view class="select_room">
						<uni-data-select
							v-model="roomActive"
							:localdata="handledSelectedRooms"
							@change="handleSelectRoomChange"
							:clear="false"
						></uni-data-select>
					</view>
				</view>
				<view class="tag-wrap">
					<view class="tag" v-for="(it, i) in selectDateTagList" :key="i">
						{{it.join(' - ')}}
					</view>
					<p v-if="!selectDateTagList.length">无预约</p>
				</view>
				<uni-calendar 
					:insert="true"
					:lunar="true" 
					:selected="selected"
					:start-date="startDate"
					:end-date="endDate"
					:showMonth="false"
					@change="handleCalendarChange"
				/>
			</view>
			
		</scroll-view>
		<w-picker
			mode="shortTerm"
			:visible.sync="isShowPicker"
			current
			expand="30"
			@confirm="handleSelectPickerDate"
			@cancel="isShowPicker = false"
		></w-picker>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	const db = uniCloud.database()
	export default {
		name: "select-appointment-date",
		data() {
			const monthNum = 1000 * 60 * 60 * 24 * 30
			const date = new Date()
			const year = date.getFullYear()
			const month = date.getMonth() + 1 + ''
			const day = date.getDate() + ''
			const nowDay = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
			return {
				dining_date_: [],
				selectDateIndex: 0,
				isShowPicker: false,
				roomActive: 0,
				startDate: nowDay,
				endDate: new Date(Date.now() + monthNum).toLocaleDateString(),
				selectCalendarValue: nowDay,
			}
		},
		props: ['modelValue', 'dining_place', 'appointment_date', 'appointment_date_origin'],
		computed: {
			...mapState({
				selectedRooms: s => s.order.selectedRooms
			}),
			isBaoXiang() {
				return this.dining_place[0].place_type === '包厢'
			},
			handledSelectedRooms() {
				return this.selectedRooms.map((e, i) => ({...e, text: e.name, value: i}))
			},
			selected() {
				return Object.keys(this.appointment_date).map(k => ({
					date: k, info: `${this.appointment_date[k].length}个预约`
				}))
			},
			selectDateTagList() {
				return this.appointment_date[this.selectCalendarValue] || []
			}
		},
		methods: {
			handleCalendarChange(e) {
				this.selectCalendarValue = e.fulldate
			},
			selectPicker(i) {
				if (i && !this.dining_date_[0]) {
					uni.showToast({
						title: '请选择开始时间',
						icon: 'none'
					})
					return
				}
				this.selectDateIndex = i
				this.isShowPicker = true
			},
			handleSelectRoomChange(index) {
				this.$emit('selectRoom', index)
			},
			handleSelectPickerDate(e) {
				const {value: date, label: dateText} = e.obj.date
				const {value: hour, label: hourText} = e.obj.hour
				const {value: minute, label: minuteText} = e.obj.minute
				const handleDate = `${date} ${hour}:${minute}`
				const selectDate = +new Date(handleDate)
				const now = new Date()
				const year = now.getFullYear()
				const month = now.getMonth() + 1
				const day = now.getDate()
				const h = now.getHours()
				const m = now.getMinutes()
				const nowDate = +new Date(`${year}-${month}-${day} ${h}:${m}:00`)
				const beforeDate = +new Date(this.dining_date_[0] || new Date())
				if (!this.selectDateIndex && selectDate < nowDate) {
					uni.showModal({
					  content: '开始时间不可小于当前时间',
					  showCancel: false
					})
					return
				} else if (this.selectDateIndex && selectDate < beforeDate) {
					uni.showModal({
					  content: '结束时间不可小于开始时间',
					  showCancel: false
					})
					return
				} else if (this.selectDateIndex && new Date(selectDate).toLocaleDateString() !== new Date(beforeDate).toLocaleDateString()) {
					uni.showModal({
					  content: '结束时间与开始时间需在同一天',
					  showCancel: false
					})
					return
				}
				if (!this.selectDateIndex) {
					this.$set(this.dining_date_, 1, '')
				}
				this.$set(this.dining_date_, this.selectDateIndex, handleDate)
				this.isShowPicker = false
			},
			async selectDateConfirm() {
				let flag = true
				const bq_flag = this.dining_date_.length < 2
				if (bq_flag) {
					uni.showToast({title: '请完善订餐时间', icon: 'none'})
					return
				} 
				uni.showLoading({title: '加载中',mask: true});
				const ids = this.selectedRooms.map(e => `\"${e._id}\"`)
				const res = await db.collection('dish-dining-place').where(`_id in [${ids}]`).get()
				const appointment_date_origin = res.result.data.map(e => e.appointment_date).flat()
				const [start, end] = appointment_date_origin.reduce((count, it) => {
					const [select_startDate, select_endDate] = this.dining_date_
					const [item_startDate, item_endDate] = it
					const _select_startDate = +new Date(select_startDate)
					const _select_endDate = +new Date(select_endDate)
					const _item_startDate = +new Date(item_startDate)
					const _item_endDate = +new Date(item_endDate)
					if (_select_startDate >= _item_startDate && _select_startDate <= _item_endDate) {
							count[0]++
					} else if (_select_endDate >= _item_startDate && _select_endDate <= _item_endDate) {
						count[1]++
					}
					return count
				}, [0, 0])
				uni.hideLoading()
				if (start || end) {
					flag = false
					uni.showModal({
						title: '提示',
						content: '你选择的时间已经有人选择了, 是否继续选择?',
						success: (res) => {
							if (res.confirm) {
								this.$emit('update:modelValue', this.dining_date_)
								this.$emit('close')
							}
						}
					});
				}
				
				if (flag) {
					this.$emit('update:modelValue', this.dining_date_)
					this.$emit('close')
				}
			},
		}
	}
</script>

<style lang="scss">
	page {
		--tag-font-size: 30rpx;
		--tag-line-height: 40rpx;
	}
	.uni-select {
		font-size: 28rpx;
		height: 70rpx;
	}
	.uni-select__input-box {
		height: 70rpx;
	}
	.select_date_wrap {
		max-height: 70vh;
		padding-bottom: 20rpx;
		font-size: 30rpx;
		.select_date_header {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 30rpx;
			border-bottom: 1px solid #f4f4f4;
			p {
				width: 100rpx;
				height: 100%;
				color: #67C23A;
				text-align: center;
				line-height: 100rpx;
			}
		}
		.appointment_date_wrap {
			padding: 20rpx;
			.subTitle {
				color: #c1c1c1;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				.select_room {
					width: 300rpx;
					margin-left: 20rpx;
					color: black;
				}
			}
			.tag-wrap {
				padding-top: 10rpx;
				min-height: 60rpx;
				max-height: 180rpx;
				overflow-y: auto;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				.tag {
					width: 206rpx;
					font-size: 30rpx;
					line-height: 40rpx;
					text-align: center;
					color: #1989fa;
					border-radius: 6rpx;
					border: 1px solid #1989fa;
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 10rpx calc((100% - 210rpx * 3) / 3 / 2);
				}
				p {
					width: 100%;
					text-align: center;
					color: #c1c1c1;
					font-size: 26rpx;
				}
			}
		}
		.form_item {
			display: flex;
			align-items: center;
			padding: 20rpx;
			.date_block {
				width: 350rpx;
				display: flex;
				align-items: center;
				margin-left: 20rpx;
				border: 1px solid #f4f4f4;
				border-radius: 20rpx;
				padding: 10rpx 20rpx;
				color: #c1c1c1;
				
				p {
					margin-left: 20rpx;
				}
			}
		}
	}
</style>